package ctx

import (
	"context"

	"gitee.com/mkwchecking/k-scaffold/pkg/rely/errors"
)

func Get[T any](ctx context.Context, key any) (T, error) {
	val := ctx.Value(key)
	if val == nil {
		return *new(T), errors.ErrResourceNotFound.WithMsg("resource not found")
	}

	v, ok := val.(T)
	if !ok {
		return *new(T), errors.ErrBadCall.WithMsg("resource is not " + string(key.(string)))
	}

	return v, nil
}

func Set(ctx context.Context, key any, value any) context.Context {
	return context.WithValue(ctx, key, value)
}
